'use strict';

app.controller('DeviceCtrl',
['$scope','$http', 'dialogs', '$uibModal', '$state', 'DeviceService',
function($scope, $http, dialogs, $uibModal, $state, DeviceService) {
	var vm = $scope.vm = this;
//	vm.animationsEnabled = true;
//    vm.toggleAnimation = function () {
//        vm.animationsEnabled = !vm.animationsEnabled;//动画效果
//    };
	var defaultQuery = {searchType:""};
	vm.query = angular.copy(defaultQuery);
	
	vm.flexigridObj = {};	
	vm.options = DeviceService.getGridOptions();

	//查询
	vm.search = function(){
		var param = angular.copy(vm.query);
		param[param.searchType] = param.keyword;
		delete param.searchType;
		delete param.keyword;
		vm.flexigridObj.flexOptions({
			newp: 1,
			extParam: param
		}).flexReload();
	}

	// 重置
	vm.reset = function(){
		vm.query = angular.copy(defaultQuery);
		vm.search();
	}
	
	// 新增
	vm.add = function(){
		$state.go('setting.deviceAdd');
	}
	// 修改
	vm.update = function(id){
		$state.go('setting.deviceUpdate', {id: id});
	}
	// 删除
	vm.del = function(index){
		var data = vm.flexigridObj.getRawRecords(index);
		// 弹出确认删除提示信息
		var dlg = dialogs.confirm(getMessage("common.deleteConfirm"));
		dlg.result.then(function(param){
			DeviceService.remove(data).then(function(data){
				// 刷新列表
				vm.flexigridObj.flexReload();
            	//弹出提示信息
            	dialogs.notify(data);
			});
		});
	}
//	 var modalInstance = $uibModal.open({
//         animation: vm.animationsEnabled,//打开时的动画开关
//         templateUrl: 'app/modules/basic/device/devicesetList.html',//模态框的页面内容,这里的url是可以自己定义的,可以是一个路径，也可以是一个模块的ID
//         controller: 'DevicesetCtrl',//这是模态框的控制器,是用来控制模态框的
//         resolve: {//这是一个入参,这个很重要,它可以把主控制器中的参数传到模态框控制器中
//             param: function () {//param是一个回调函数
//                 return param;//这个值会被模态框的控制器获取到
//             }
//         }
//     });
//     modalInstance.result.then(function (result) {//这是一个接收模态框返回值的函数
//        var result = result;//模态框的返回值
//     });
   //设置查询的设置名称
     vm.setQueryDevicesetList = function () {
                 var param = vm.query.devicesetList;
                 var modalInstance = $uibModal.open({
                     animation: false,
                     backdrop:true,
                     templateUrl: 'tpl/blocks/setting/device/deviceSetList.html',
                     controller: 'DevicesetCtrl',
                     resolve: {
                         param: function () {
                             return param;
                         }
                     }
                 });
                 modalInstance.result.then(function (result) {//这是一个接收模态框返回值的函数
                     vm.query.deviceList = result;//模态框的返回值
                     vm.showQueryDeviceList = getSelectDevice( vm.query.deviceList);
                 });
             };

}]);

//模态框控制器
app.controller('DevicesetCtrl', ['$scope', '$state', '$uibModalInstance', 'dialogs', 'DeviceService', 'param',
                                     function ($scope, $state, $uibModalInstance, dialogs, DeviceService, param) {

                                         var vm = $scope.vm = this;
                                         vm.devicesetList = param;

                                         vm.saveDevicesetList = function () {
                                             var result = vm.devicesetList;
                                             $uibModalInstance.close(result);
                                         };

                                         vm.cancelDevicesetList = function () {
                                             //dismiss也是在模态框关闭的时候进行调用,而它返回的是一个reason
                                             $uibModalInstance.dismiss('cancel');
                                         };

                                  }]);

app.controller('DeviceAddOrUpdateCtrl', ['$scope', '$http', '$state',  'dialogs', 'DeviceService',
function($scope, $http, $state , dialogs, DeviceService){
	var vm = $scope.vm = this;
	vm.user = {id:''};
	vm.isEdit = false;

	
	function cancel(){
		$state.go('setting.device.list');
	};

//	var initDataPromise = UserService.getInitData($state.params.id).then(function(data){
//		vm.roleList = data.roleList;
//	});
	
	vm.title="user.xinzeng";
	if(!ISS.isEmpty($state.params.id)){
		vm.isEdit = true;
		vm.title="user.xiugaiyonghu";
		vm.device.id = $state.params.id;
		initDataPromise.then(function(){
			DeviceService.initUpdate($state.params.id).then(function(data){
				if(data.success === false){
					dialogs.notify(data);
					cancel();
				}else{
					vm.device = data;
					vm.selectRoles = [];
					angular.forEach(vm.roleList, function(u){
						if(u.checked){
							vm.selectRoles.push(u);
						}
					});
				}
			},function(){
				cancel();
			});
		})
	}

	vm.treeObj = {};
	vm.treeSetting = {
		check: {
			enable: true
		},
		data: {
			simpleData: {
				enable: true
			}
		},
		callback : {
			onAsyncSuccess: function(){
				onClickNode();
			},
			onCheck : onClickNode
		}
	};

	//回调
	function onClickNode(event, treeId, treeNode)
	{
		vm.device.archs = [];
	 	var checkedNodes = vm.treeObj.getCheckedNodes(true);
		angular.forEach(checkedNodes, function(node) {
			var area = {id: node.id};
			if (node.id != 0){
				vm.user.archs.push(area);
			}
		});
	}
	//****************
	$http.post(ISS.getPath('/user/treeArea?userId=' + vm.user.id)).then(function(resp){
		if(ISS.isNotEmpty(resp.data))
		{
			var root = {id:0,name:ISS.getMessage('area.rootName')};
			angular.forEach(resp.data, function(node) {
				if (node.checked){
					root.checked = true;
				}
			});
			resp.data.push(root);
			vm.treeObj.reRender(vm.treeSetting, resp.data);
		}		
	});
	
	vm.cancel = function(){
		cancel();
	};
	
//	function processData(){
//		//角色
//		vm.user.roles = [];
//		angular.forEach(vm.selectRoles, function(role){
//			vm.user.roles.push(angular.copy(role));
//		});
//	}
	// 提交数据
	vm.save = function(){
		
		processData();
		
		if(ISS.isEmpty(vm.device.id)){
			DeviceService.add(vm.device)
			.then(function(data){
				if(data.success){
					dialogs.notify(data).closed.then(function(){
						cancel();
					});
				}else{
					dialogs.notify(data);
				}	
			});
		}else{
			DeviceService.update(vm.device)
			.then(function(data){
				if(data.success){
					dialogs.notify(data).closed.then(function(){
						cancel();
					});
				}else{
					dialogs.notify(data);
				}	
			});
		}
	};
	
}]);

//经纬度选择
app.controller('latLngSelectCtrl',function($scope, $uibModalInstance, data){
	var vm = $scope.vm = this;
	
	$scope.myMap = null;
	vm.mapOptions = {zoom: 10};
	//选择的经纬度
	vm.selectLngLat = '';
	vm.lng = '';
	vm.lat = '';
	
	vm.mapClick = function(e, param){
		if(ISS.mapType == 'google'){
			vm.lng = param[0].latLng.lng();
			vm.lat = param[0].latLng.lat();
			if(ISS.isNotEmpty(vm.lng)){
				var sp = (vm.lng+'').split('.');
				if(sp.length > 1 && sp[1].length > 6){
					vm.lng = sp[0] + '.' + sp[1].substr(0,6);
				}
			}
			if(ISS.isNotEmpty(vm.lat)){
				var sp = (vm.lat+'').split('.');
				if(sp.length > 1 && sp[1].length > 6){
					vm.lat = sp[0] + '.' + sp[1].substr(0,6);
				}
			}
		}else if(ISS.mapType == 'amap'){
			vm.lng = param[0].lnglat.getLng();
			vm.lat = param[0].lnglat.getLat();
	    }
		vm.selectLngLat = vm.lng + ',' + vm.lat;
	}
	
	vm.cancel = function(){
		$uibModalInstance.dismiss('Canceled');
	}; // end cancel
	
	vm.save = function(){
		$uibModalInstance.close({
			lng:vm.lng,
			lat:vm.lat
		});
	}; // end save
	
	
});

//地图经纬度选择组件
app.component('mapSelect', {
    bindings: {
        location:'=',
        onSelect:'='
    },
    controller: ['$scope','$element', '$attrs', 'dialogs', function(scope, el, attr, dialogs){
        var vm = scope.vm = this;

        vm.setLocation = function(){
            var dlg = dialogs.create(
                ISS.getResPath('tpl/blocks/dlgs/latLanSelect-dlg.html'),
                'latLngSelectCtrl',
                vm.location,
                {size:'md', backdrop: false}
            );
            dlg.result.then(function(lngLat){
                if(vm.onSelect){
                    vm.onSelect(lngLat);
                }
            });
        }
    }],
    template:'<button class="btn m-b-none btn-default padder-2" ng-click="vm.setLocation()" translate="common.location"></button>'
});

